package com.example.ls_work

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.app.Application
import android.os.Build
import android.view.WindowManager
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class MainActivity: FlutterActivity(), Application.ActivityLifecycleCallbacks {
    private val CHANNEL = "native_utils"
//    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
//        GeneratedPluginRegistrant.registerWith(flutterEngine) // add this line
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        application.registerActivityLifecycleCallbacks(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        application.unregisterActivityLifecycleCallbacks(this)
    }

    override fun onActivityCreated(
        activity: Activity,
        savedInstanceState: Bundle?
    ) {

    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {
        if (activity == this && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND)
        }
    }

    override fun onActivityPaused(activity: Activity) {
        if (activity == this && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND
            )
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                window.attributes.blurBehindRadius = 100
            }
        }

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(
        activity: Activity,
        outState: Bundle
    ) {

    }

    override fun onActivityDestroyed(activity: Activity) {

    }


    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
                call, result ->
            when (call.method) {
                "showNativeToast" -> {
                    val message = call.argument<String>("message")
                    showToast(applicationContext, message)
                    result.success(null)
                }
                "setSecureScreen" -> {
                    val secure = call.argument<Boolean>("secure") ?: false
                    setSecureFlag(secure)
                    result.success(null)
                }
                "isSecureScreen" -> {
                    result.success(isSecureFlagSet())
                }
                "androidSdkInt"->{
                    result.success(Build.VERSION.SDK_INT)
                }


                "compressImage"->{
                    val imagePath = call.argument<String>("imagePath")
                    val maxWidth = call.argument<Int>("maxWidth") ?: 1024
                    val maxHeight = call.argument<Int>("maxHeight") ?: 1024
                    val quality = call.argument<Int>("quality") ?: 80

                    if (imagePath != null) {
                        try {
                            val compressedPath = compressImage(imagePath, maxWidth, maxHeight, quality)
                            result.success(compressedPath)
                        } catch (e: Exception) {
                            result.error("COMPRESS_ERROR", e.message, null)
                        }
                    } else {
                        result.error("INVALID_PATH", "图片路径不能为空", null)
                    }
                }
                "checkRootOrJailbreak"->{
                    val isRooted = checkRoot()
                    result.success(isRooted)
                }
                else -> result.notImplemented()
            }
        }
    }

    private fun setSecureFlag(secure: Boolean) {
        if (secure) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }
    }

    private fun isSecureFlagSet(): Boolean {
        return window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE != 0
    }

    private fun showToast(context: Context, message: String?) {
        Toast.makeText(context, message ?: "App is in background", Toast.LENGTH_LONG).show()
    }


    private fun compressImage(imagePath: String, maxWidth: Int, maxHeight: Int, quality: Int): String {
        val file = File(imagePath)
        if (!file.exists()) {
            throw IOException("文件不存在")
        }

        // 解码图片并计算缩放比例
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(imagePath, options)

        val originalWidth = options.outWidth
        val originalHeight = options.outHeight
        var scale = 1

        // 计算缩放比例
        if (originalWidth > maxWidth || originalHeight > maxHeight) {
            val widthRatio = originalWidth.toFloat() / maxWidth.toFloat()
            val heightRatio = originalHeight.toFloat() / maxHeight.toFloat()
            scale = Math.max(widthRatio, heightRatio).toInt()
        }

        // 重新解码图片
        options.inJustDecodeBounds = false
        options.inSampleSize = scale
        options.inPreferredConfig = Bitmap.Config.RGB_565

        val bitmap = BitmapFactory.decodeFile(imagePath, options) ?: throw IOException("解码图片失败")

        // 创建输出文件
        val outputDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val outputFile = File(outputDir, "compressed_${System.currentTimeMillis()}.jpg")

        // 压缩并保存图片
        FileOutputStream(outputFile).use { out ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)
        }
        bitmap.recycle()

        return outputFile.absolutePath
    }

    private fun checkRoot(): Boolean {
        // 检查常见的Root迹象
        return checkRootFiles() ||
                checkRootPackages() ||
                checkSuBinary() ||
                checkRootProps() ||
                checkDangerousProps()
    }

    private fun checkRootFiles(): Boolean {
        // 常见的Root相关文件
        val rootFiles = arrayOf(
            "/system/app/Superuser.apk",
            "/sbin/su",
            "/system/bin/su",
            "/system/xbin/su",
            "/data/local/xbin/su",
            "/data/local/bin/su",
            "/system/sd/xbin/su",
            "/system/bin/failsafe/su",
            "/data/local/su",
            "/su/bin/su"
        )
        return rootFiles.any { File(it).exists() }
    }

    private fun checkRootPackages(): Boolean {
        // 常见的Root管理应用包名
        val rootPackages = arrayOf(
            "com.noshufou.android.su",
            "com.thirdparty.superuser",
            "eu.chainfire.supersu",
            "com.koushikdutta.superuser",
            "com.zachspong.temprootremovejb",
            "com.ramdroid.appquarantine"
        )
        val pm = applicationContext.packageManager
        return rootPackages.any {
            try {
                pm.getPackageInfo(it, 0)
                true
            } catch (e: Exception) {
                false
            }
        }
    }

    private fun checkSuBinary(): Boolean {
        // 检查su命令是否存在
        val places = arrayOf(
            "/system/bin/", "/system/xbin/", "/sbin/",
            "/system/sd/xbin/", "/system/bin/failsafe/",
            "/data/local/xbin/", "/data/local/bin/",
            "/data/local/"
        )
        return places.any {
            try {
                File(it + "su").exists()
            } catch (e: Exception) {
                false
            }
        }
    }

    private fun checkRootProps(): Boolean {
        // 检查系统属性
        val buildTags = android.os.Build.TAGS
        return buildTags != null && buildTags.contains("test-keys")
    }

    private fun checkDangerousProps(): Boolean {
        // 检查危险的系统属性
        try {
            val process = Runtime.getRuntime().exec("getprop ro.debuggable")
            val input = process.inputStream.bufferedReader()
            val output = input.use { it.readText().trim() }
            return output == "1"
        } catch (e: Exception) {
            return false
        }
    }
}
